<template>
  <div class="app-container">
    <el-card shadow="always">
      <div class="title">
        <span />
        <p>查询条件</p>
      </div>

      <el-form :model="seachForm" label-width="120px">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="仓库名称：">
              <el-input
                v-model="seachForm.fileName"
                placeholder="请输入仓库名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" style="text-align: right">
            <el-button type="primary" @click="getInit(1)">查询</el-button>
            <el-button @click="rest">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="always" style="margin-top: 15px">
      <div class="header">
        <div class="title">
          <span />
          <p>仓库列表</p>
        </div>

        <div>
          <el-button
            type="primary"
            size="small"
            @click="sync_gitee"
            :loading="sync_loading"
            >同步</el-button
          >
        </div>
      </div>

      <TableView
        :data-list="dataList"
        :loading="loading"
        :total="seachForm.total"
        :size="seachForm.size"
        :page="seachForm.page"
        @pagination="pagination"
      >
        <div slot="column">
          <el-table-column
            label="仓库名称"
            align="center"
            prop="name"
            width="300"
            show-overflow-tooltip
          />

          <el-table-column
            label="是否私有"
            align="center"
            show-overflow-tooltip
            width="100"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.private ? 'danger' : 'success'"
                disable-transitions
              >
                {{ scope.row.private ? "私有" : "公开" }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 仓库创建时间 -->
          <el-table-column
            label="仓库创建时间"
            align="center"
            prop="created_at"
            width="250"
            show-overflow-tooltip
          />

          <el-table-column
            label="最后更新时间"
            align="center"
            prop="updated_at"
            width="250"
            show-overflow-tooltip
          />

          <el-table-column
            label="克隆地址"
            align="center"
            prop="html_url"
            width="350"
            show-overflow-tooltip
          />

          <el-table-column
            label="描述"
            align="center"
            prop="description"
            show-overflow-tooltip
            width="250"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.description || "---" }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            min-width="300"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="commit_store(scope.row)"
                :disabled="env != 'development'"
                >提交至仓库</el-button
              >
              <el-button type="text" @click="look_push_history(scope.row)"
                >提交记录</el-button
              >
            </template>
          </el-table-column>
        </div>
      </TableView>
    </el-card>

    <!-- 提交记录 -->
    <el-dialog
      title="提交记录"
      :visible.sync="show_git_push_history"
      width="50%"
    >
      <div
        style="width: 100%; height: 70vh; display: flex; flex-direction: column"
        v-loading="pushHistoryLoading"
      >
        <h2 style="width: 100%; height: 40px">
          {{ repoName }} 仓库提交记录
          <el-select
            placeholder="请选择分支"
            v-model="branchName"
            @change="getPushHistory"
          >
            <el-option
              v-for="(item, index) in branchList"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </h2>

        <ul v-if="pushHistory.length > 0" class="list">
          <li v-for="(commit, index) in pushHistory" :key="index">
            <p><strong>提交哈希:</strong> {{ commit.sha }}</p>
            <p><strong>作者:</strong> {{ commit.commit.author.name }}</p>
            <p><strong>提交信息:</strong> {{ commit.commit.message }}</p>
            <p>
              <strong>提交时间:</strong>
              {{ commit.commit.author.date }}
            </p>
          </li>
        </ul>
        <p v-else>暂无提交记录</p>
      </div>
    </el-dialog>

    <!-- is_show_commit_store -->
    <el-dialog
      title="向该仓库提交数据"
      :visible.sync="is_show_commit_store"
      width="50%"
    >
      <el-form
        :model="commitForm"
        label-width="110px"
        :rules="rules"
        ref="form"
      >
        <el-form-item label="远程仓库地址">
          <el-input
            placeholder="请输入远程仓库地址"
            v-model="commitForm.html_url"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item label="本地项目地址" prop="localRepoPath">
          <el-input
            placeholder="请输入本地仓库地址"
            v-model="commitForm.localRepoPath"
            @change="diff_store"
          >
            <template slot="suffix">
              <el-dropdown trigger="click" @command="clickHistory">
                <span style="cursor: pointer">历史地址</span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(item, index) in rowObj.localRepoPaths"
                    :key="index"
                    :command="item"
                    >{{ item }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="分支" prop="branchName">
          <el-select placeholder="请选择分支" v-model="commitForm.branchName">
            <el-option
              v-for="(item, index) in branchList"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="commitForm.username"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="commitForm.password"
            type="password"
          ></el-input>
        </el-form-item>

        <el-form-item label="提交信息">
          <el-input
            placeholder="请输入提交信息"
            v-model="commitForm.commit_message"
          ></el-input>
        </el-form-item>

        <el-form-item label="差异" v-if="disffLoading || disff">
          <div
            style="
              width: 100%;
              height: 250px;
              overflow-y: auto;
              border: 1px solid #ccc;
              padding: 10px;
              box-sizing: border-box;
            "
            v-loading="disffLoading"
          >
            <p style="white-space: pre-wrap">{{ disff || "---" }}</p>
          </div>
        </el-form-item>
      </el-form>

      <div style="text-align: center">
        <el-button type="primary" @click="submit" :loading="submitLoading"
          >提交</el-button
        >
        <el-button @click="is_show_commit_store = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  checkDiff,
  commit,
  getGitList,
  git_branch_message,
  git_history_message,
  gitmanageDel,
  gitmanageUpdate,
  sync_git,
} from "@/api/databaseManagement";
import TableView from "@/components/TableView/index.vue";
import moment from "moment";
export default {
  components: {
    TableView,
  },
  data() {
    return {
      dataList: [],
      loading: false,
      seachForm: {
        page: 1,
        size: 10,
        total: 0,
      },

      sync_loading: false,

      // git 提交记录
      show_git_push_history: false,
      pushHistory: [],
      repoName: "",
      branchList: [],
      branchName: "",
      pushHistoryLoading: false,
      is_show_commit_store: false,
      commitForm: {},
      disff: "",
      disffLoading: false,

      // 提交代码的表单校验
      rules: {
        localRepoPath: [
          {
            required: true,
            message: "请输入本地文件地址",
            trigger: ["blur", "change"],
          },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        branchName: [
          { required: true, message: "请选择分支", trigger: "change" },
        ],
      },

      rowObj: {},
      submitLoading: false,
      env: process.env.VUE_APP_ENV,
    };
  },

  mounted() {
    this.getInit();
  },

  methods: {
    async getInit(page) {
      this.seachForm.page = page || this.seachForm.page;
      this.loading = true;
      const res = await getGitList(this.seachForm);
      if (res.code == 20000) {
        this.dataList = res.data || [];

        this.seachForm.total = res.total;
      } else {
        this.$message.error(res.msg);
      }
      this.loading = false;
    },

    rest() {
      this.seachForm = {};
      this.getInit();
    },

    // 同步仓库
    async sync_gitee() {
      try {
        this.sync_loading = true;
        let result = await sync_git({});
        if (result.code == 20000) {
          this.$message.success(result.msg);
          this.getInit();
        } else {
          this.$message.error(result.msg);
        }
        this.sync_loading = false;
      } catch (error) {
        this.$message.error(error);
        this.sync_loading = false;
      }
    },

    // 查看提交记录
    async look_push_history(item) {
      try {
        this.pushHistory = [];
        this.branchList = [];
        this.pushHistoryLoading = true;
        this.show_git_push_history = true;
        this.repoName = item.name;
        // 获取分支信息
        await this.gettBranchList(item);
        // 查看提交记录
        await this.getPushHistory();
        this.pushHistoryLoading = false;
      } catch (error) {
        this.$message.error("操作失败" + error);
      }
    },

    // 获取提交记录
    async getPushHistory() {
      try {
        // 获取第一个一个分支的提交记录
        let result = await git_history_message({
          repo_name: this.repoName,
          branchName: this.branchName,
        });
        if (result.code == 20000) {
          this.pushHistory = result.data;
          this.pushHistory.forEach((item) => {
            item.commit.author.date = moment(item.commit.author.date).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          });
        } else {
          this.$message.error(result.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },

    // 获取分支信息
    async gettBranchList(item) {
      try {
        let branch = await git_branch_message({ repo_name: item.name });
        this.branchList = branch.data || [];
        this.branchName = branch.data[0].name; //默认显示分支列表第一个分支
      } catch (error) {
        this.$message.error(error);
      }
    },

    // 向远程仓库提交文件
    async commit_store(item) {
      this.commitForm = {};
      this.disff = "";
      this.gettBranchList(item);
      // 获取本地仓库与远程仓库之间的差异
      this.is_show_commit_store = true;
      this.commitForm.html_url = item.html_url;
      this.rowObj = item;
    },

    async submit() {
      this.$refs.form.validate(async (flag) => {
        if (flag) {
          try {
            if (!this.disff) {
              this.$message.warning("暂无更改，无需提交");
              return;
            }
            this.submitLoading = true;
            let result = await commit(this.commitForm);
            console.log(result, "result");

            if (result.code == 20000) {
              this.$message.success(result.msg);
              this.is_show_commit_store = false;

              // 记录本次提交的本地项目地址，如果存在原来存在 就不追加
              if (
                !this.rowObj.localRepoPaths.includes(
                  this.commitForm.localRepoPath
                )
              ) {
                this.rowObj.localRepoPaths.push(this.commitForm.localRepoPath);
                console.log(
                  this.rowObj.localRepoPaths,
                  "this.rowObj.localRepoPaths"
                );
                gitmanageUpdate(this.rowObj);
              }
            } else {
              this.$message.error(result.msg);
            }
            this.submitLoading = false;
          } catch (error) {
            console.dir(error, "error");
            this.$message.error(error);
            this.submitLoading = false;
          }
        }
      });
    },

    // 查看本地仓库与远程仓库之间的差异
    async diff_store() {
      if (!this.commitForm.localRepoPath) {
        return;
      }

      this.disffLoading = true;
      try {
        let result = await checkDiff(this.commitForm);
        if (result.code == 20000) {
          this.disff = result.data;
        } else {
          this.disff = "";
        }
        this.disffLoading = false;
      } catch (error) {
        this.disff = "";
        this.disffLoading = false;
      }
    },

    pagination(e) {
      this.seachForm = e;
      this.getInit();
    },

    // 点击历史地址 将历史保存的地址 赋值给本地地址 ， 然后获取差异信息
    clickHistory(e) {
      this.$set(this.commitForm, "localRepoPath", e);
      this.diff_store();
    },
  },
};
</script>

<style scoped>
.list {
  list-style-type: none;
  padding: 0;
  flex: 1;
  width: 100%;

  overflow-y: auto;
}

.list li {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}
</style>
